/**
 * Created by shenhai on 15/9/5.
 */


var async = require('async');
var mysqlUtil = require('../../../common/utils/mysqlUtil');
var User = mongoose.model('user');
var Community = mongoose.model('community');
var CommunitySupplement = mongoose.model('community_supplements');
var CommunityApplications = mongoose.model('community_applications');
var UserCommunity = mongoose.model('user_community');
var Apply = mongoose.model('community_applications');
var Region = mongoose.model('masterData_Regions');
var CommunityImport = mongoose.model('community_import_record');
var node_xj = require("xls-to-json");
var fs = require('fs');
var geolib = require('geolib');
var pinyin = require('transliteration').slugify;
var toolUtil = require('../../../common/utils/toolUtil');
var Cache = require('../../../common/utils/cacheUtil.js');
exports.shouldAddCommunity = function(option, callback) {

    Community.count(option, function(err, result) {
        callback(null, result > 0);
    });
};


var getPinyin = function(str) {
    return pinyin(str, {lowercase: true, separator:''});
};

var getPinyinShort = function(str) {
    var small = pinyin(str, {lowercase: true, separator:' '});
    small = small.replace(/\b\w+\b/g, function(word){
        return word.substring(0,1).toLowerCase()}
    );
    if (!small) return '';
    return small.replace(/\s+/g, "");
};

//var large = pinyin(req.body.str, {lowercase: true, separator:''});
//
//var small = pinyin(req.body.str, {lowercase: true, separator:' '});
//small = small.replace(/\b\w+\b/g, function(word){
//        return word.substring(0,1).toLowerCase()}
//);
//small = small.replace(/\s+/g, "");


exports.communityListService = function(req ,callback) {

    var body = req.body;
    var size = Number(req.params.size);
    var index = (Number(req.params.page) - 1) * size;
    var paged = (req.params.size && req.params.page);

    var option = {};
    var sortType = paged ? {dateLastModified:-1} : {};

    if (body.id) option._id = body.id;
    if (body.city) option.cityId = body.city;
    if (body.communityName) option.communityName = new RegExp(body.communityName);
    if (body.valid) option.isValid = body.valid;

    if (body.init) {
         if(body.init =='0'){
             option['$or'] = [{isInit:{$exists: false}},{isInit:false}];
         }else{
             option.isInit = body.init;
         };
    }



    logger.debug(option);

    async.series([

        function (callbackInner) {
            Community.count(option, function (err, count) {

                if (err) {
                    callbackInner(err, null);
                }else {
                    var temp = {count: count, totalPage:Math.ceil(count/size)};
                    callbackInner(err, temp);
                }
            });
        },
        function (callbackInner) {

            if (paged) { // 分页

                logger.debug(option);
                logger.debug('分页');

                Community.find(option).sort(sortType).skip(index).limit(size)
                    .populate('provinceId', '_id name')
                    .populate('cityId', '_id name')
                    .populate('countyId', '_id name')
                    .exec(function (err, results) {

                        async.each(results, function (community, callbackInner2) {
                            //logger.debug(community._id);
                            User.count({community:community._id}, function (err, count) {
                                community._doc.uCount = count;
                                callbackInner2(null,community);
                            });

                        }, function (err) {
                            callbackInner(err, results);
                        });

                });

            }else { // 不分页

                logger.debug('不分页');
                option = body;
                if (option.communityName) {
                    var reg= /[A-Za-z]/g;
                    if (reg.test(option.communityName)) {
                        option.pinyinShort = new RegExp(option.communityName);
                        delete option.communityName;
                    }else {
                        option.communityName = new RegExp(option.communityName);
                    }
                }

                logger.debug(option);

                // city provinceId cityId countyId
                Community.find(option,'_id communityName').sort(sortType).exec(function (err, results) {

                    callbackInner(err, results);
                });

            }



        }], callback);


};


exports.communityAddService = function(req ,callback) {

    var body = req.body;
    body.isValid = true;

    logger.debug(req.body);
    if (!(body.provinceId && body.cityId && body.countyId && body.city && body.communityName && body.communityAddress  && body.longitude && body.latitude)) {
        callback( {message : "缺少小区基础数据"},null);
        return;
    }

    async.series([

        function (callbackInner) {

            var option = {
                communityName: body.communityName,
                provinceId: body.provinceId,
                cityId: body.cityId,
                countyId: body.countyId,
                city: body.city,
                location: {
                    longitude: Number(body.longitude),
                    latitude: Number(body.latitude)
                }
            };

            Community.count(option, function(err, result) {

                if (result != 0) {
                    callbackInner({message :"小区信息重复"});
                }else {
                    callbackInner(err, result);
                }
            });
        },

        function (callbackInner) {

            var data = {
                communityName: body.communityName,
                pinyin:getPinyin(body.communityName),
                pinyinShort:getPinyinShort(body.communityName),
                communityAddress: body.communityAddress,
                communityPostCode: body.communityPostCode,
                city: body.city,
                location: {
                    longitude: Number(body.longitude),
                    latitude: Number(body.latitude)
                },
                phoneList: [
                    {name:'物业',phoneNo:'',address:''},
                    {name:'居委会',phoneNo:'',address:''},
                    {name:'小区民警',phoneNo:'',address:''}
                ],
                isValid:true
            };


            if (body.provinceId)  data.provinceId = body.provinceId;
            if (body.cityId)  data.cityId = body.cityId;
            if (body.countyId)  data.countyId = body.countyId;

            if (body.households) data.households = Number(body.households);
            if (body.communityLogo) data.communityLogo = body.communityLogo;
            if (body.effectiveDate) data.dateEffective = body.effectiveDate;
            data.unitSwitch = body.unitSwitch ? true:false;


            if (body.subdistrict) data.subdistrict = body.subdistrict; //行政子区域
            if (body.developer) data.developer = body.developer; //开发商
            if (body.propertyType) data.propertyType = body.propertyType; //小区住宅类型
            if (body.property) data.property = body.property; //物业
            if (body.constructionArea) data.constructionArea = body.constructionArea; //小区占地面积
            if (body.dateBuild) data.dateBuild = body.dateBuild; //小区建造日期
            if (body.desc) data.desc = body.desc;  //小区描述
            if (body.price) data.price = Number(body.price); //价格
            if (body.rent) data.rent = Number(body.rent); //租
            if (body.sale) data.sale = Number(body.sale); //出售

            logger.debug(data);
            var temp = new Community(data);
            temp.save(function (err, result) {
                if(!err) toolUtil.putMessageCommunityCalcAroundMQ({communityId:result._id});
                callbackInner(err, result);
            });
        }], callback);

};


exports.communityEditService = function(req ,callback) {

    var body = req.body;

    //if (!(body.provinceId && body.cityId && body.countyId && body.city && body.communityName && body.communityAddress)) {
    if (!(body.cityId  && body.city && body.communityName && body.communityAddress)) {
        return callback("缺少小区基础数据", null);
    };

    var id = body.id;
    delete body.id;


    if (body.communityName) {
        body.pinyin = getPinyin(body.communityName);
        body.pinyinShort = getPinyinShort(body.communityName);
    };

    if(body.location.longitude) body.location.longitude= Number(body.location.longitude);
    if(body.location.latitude) body.location.latitude= Number(body.location.latitude);

    logger.debug(body);

    Community.update({_id: id}, body, function(err, result){
       if(!err) toolUtil.putMessageCommunityCalcAroundMQ({communityId: id});

        callback(err,null);
    });

};


exports.communitySwitchService = function(req ,callback) {

    var body = req.body;
    logger.debug(body);
    Community.update({_id: body.id}, {isValid: body.isValid}, callback);
};


// 导入小区
exports.communityImportService = function(req ,callback) {

    var excelData = null;
    var all = 0;
    var failureAry = [];
    var num = 0;

    async.series([
        function (callbackInner) {
            if (req.files.excel != null) {

                var filePath = req.files.excel.path;
                logger.debug(filePath);

                node_xj({
                    input: filePath,  // input xls
                    output: "output.json" // output json
                }, function(err, result) {

                    fs.unlink(filePath);

                    if(err) {
                        console.error(err);
                        callbackInner(err, null);
                    } else {
                        console.log(result);
                        excelData = result;
                        all = result.length;
                        callbackInner(null, result);
                    }

                });
            }
            else {
                callbackInner(null, null);
            }
        },


        function (callbackInner) {

            async.each(excelData, function (entity, callbackInner2) {


                var res = false;
                async.series([


                    function (callbackInner3) {
                        async.series([
                            function (callbackInner4) {

                                if (entity['省']) {
                                    Region.find({type: "province", name:entity['省']}, '_id').exec(function (err, results) {
                                        entity.provinceId = results[0]._id;
                                        callbackInner4(err, results);
                                    });
                                }else {
                                    callbackInner4(null, null);
                                }
                            },

                            function (callbackInner4) {

                                if (entity['市']) {
                                    Region.find({type: "city", name:entity['市']}, '_id').exec(function (err, results) {
                                        entity.cityId = results[0]._id;
                                        callbackInner4(err, results);
                                    });
                                }else {
                                    callbackInner4(null, null);
                                }
                            },

                            function (callbackInner4) {

                                if (entity['区/县']) {
                                    Region.find({type: "county", name:entity['区/县']}, '_id').exec(function (err, results) {
                                        entity.countyId = results[0]._id;
                                        callbackInner4(err, results);
                                    });
                                }else {
                                    callbackInner4(null, null);
                                }
                            }


                        ], callbackInner3);

                    },

                    function (callbackInner3) {

                        var option = {provinceId:entity.provinceId, cityId:entity.cityId, countyId:entity.countyId, communityName:entity['小区名称']};
                        Community.count(option, function(err, result) {
                            res = result == 0;
                            callbackInner3(err,result);
                        });
                    },

                    function (callbackInner3) {

                        if (res) {
                            var data = {
                                city: entity['市'],
                                communityName: entity['小区名称'],
                                pinyin : getPinyin(entity['小区名称']),
                                pinyinShort : getPinyinShort(entity['小区名称']),
                                communityAddress: entity['小区地址'],
                                location: {
                                    longitude: entity['经度'],
                                    latitude: entity['纬度']
                                },
                                phoneList: [
                                            {name:'物业',phoneNo:'',address:''},
                                            {name:'居委会',phoneNo:'',address:''},
                                            {name:'小区民警',phoneNo:'',address:''}
                                ],
                                isValid:true
                                //communityLogo: input.communityLogo,
                                //unitSwitch: (entity['是否显示单元号开关'] == '是')
                            };
                            if (entity.provinceId) data.provinceId = entity.provinceId;
                            if (entity.cityId) data.cityId = entity.cityId;
                            if (entity.countyId) data.countyId = entity.countyId;


                            if (entity['行政子区域']) data.subdistrict = entity['行政子区域']; //行政子区域
                            if (entity['开发商']) data.developer = entity['开发商']; //开发商
                            if (entity['小区住宅类型']) data.propertyType = entity['小区住宅类型']; //小区住宅类型
                            if (entity['物业']) data.property = entity['物业']; //物业
                            if (entity['小区占地面积']) data.constructionArea = entity['小区占地面积']; //小区占地面积
                            if (entity['户数']) data.households = Number(entity['户数']);
                            if (entity['小区建造日期']) data.dateBuild = new Date(entity['小区建造日期']); // 小区建造日期
                            if (entity['小区描述']) data.desc = entity['小区描述'];  //小区描述
                            if (entity['价格(元/平方)']) data.price = Number(entity['价格(元/平方)']); //价格(元/平方)
                            if (entity['绿化率']) data.greenRate = Number(entity['绿化率']); //绿化率
                            if (entity['租']) data.rent = Number(entity['租']); //租
                            if (entity['出售']) data.sale = Number(entity['出售']); //出售


                            var temp = new Community(data);
                            temp.save(function(err, result){

                                if (err) {
                                    failureAry.push(entity['省'] + ',' +entity['市'] + ',' + entity['区/县'] +':' + entity['小区名称'] + '  ');
                                }else {
                                    toolUtil.putMessageCommunityCalcAroundMQ({communityId:result._id});
                                }

                                if (num == (all - 1)) {
                                    var temp = new CommunityImport({allRecord:all,failure:failureAry});
                                    temp.save(function(err, result) {
                                        num += 1;
                                        callbackInner3(err, result);
                                    });
                                }else {
                                    num += 1;
                                    callbackInner3(err, result);
                                }


                            });
                        }else {
                            failureAry.push(entity['市'] +':' + entity['小区名称'] + ',');
                            logger.debug("all:");
                            logger.debug(all + "," + num);
                            if (num == (all - 1)) {
                                var temp = new CommunityImport({allRecord:all,failure:failureAry});
                                temp.save(function(err, result) {
                                    num += 1;
                                    callbackInner3(err, result);
                                });
                            }else {
                                num += 1;
                                callbackInner3("小区信息重复", null);
                            }
                        }
                    }
                ], callbackInner2);

            },callbackInner);

        }], callback);
};



// 检查是否有重复经纬度
exports.testService = function(req ,callback) {

    var data = [];
    var n = 0;

    async.series([

        function (callbackInner) {
            Community.find({}, 'location', function (err, result) {
                data = result;
                callbackInner(err, result);
            });
        },

        function (callbackInner) {

            var leng = data.length;
            var tempArray = [];
            var array = [];


            for(var i = 0; i<leng; i++) {

                if (tempArray.contain(data[i].location)) {

                    if (!array.contain(data[i].location)) {
                        n++;
                        logger.debug(n + ' ' + i);
                        array.push(data[i].location);
                    }
                }else {
                    tempArray.push(data[i].location);
                }
            }
            callbackInner(null, array);
        },
    ], callback);

};

Array.prototype.contain = function (element) {

    for (var i = 0; i < this.length; i++) {
        if (this[i].longitude == element.longitude && this[i].latitude == element.latitude) {
            return true;
        }
    }
    return false;
}

exports.communityImportRecordService = function (req, callback) {

    var body = req.body;
    var size = Number(req.params.size);
    var index = (Number(req.params.page) - 1) * size;

    var option = {};
    var sortType = {dateCreated: -1};

    async.series([

        function (callbackInner) {
            CommunityImport.count(option, function (err, count) {
                var temp = {count: count, totalPage:Math.ceil(count/size)};
                callbackInner(err, temp);
            });
        },
        function (callbackInner) {
            CommunityImport.find(option)
           .sort(sortType).skip(index).limit(size).exec(function (err, results) {

                    if (err) {
                        return callbackInner(err);
                    } else {
                        return callbackInner(null, results);
                    }

                })
        }], callback);

};


// 更新线上100多个小区
exports.communityImportTestService = function(req ,callback) {


    var excelData = null;
    var all = 0;
    var failureAry = [];
    var num = 0;

    async.series([
        function (callbackInner) {
            if (req.files.excel != null) {

                var filePath = req.files.excel.path;
                logger.debug(filePath);

                node_xj({
                    input: filePath,  // input xls
                    output: "output.json" // output json
                }, function(err, result) {

                    fs.unlink(filePath);

                    if(err) {
                        console.error(err);
                        callbackInner(err, null);
                    } else {
                        console.log(result);
                        excelData = result;
                        all = result.length;
                        callbackInner(null, result);
                    }

                });
            }
            else {
                callbackInner(null, null);
            }
        },


        function (callbackInner) {

            async.each(excelData, function (entity, callbackInner2) {


                var res = false;
                async.series([


                    function (callbackInner3) {
                        async.series([
                            function (callbackInner4) {

                                if (entity['省']) {
                                    Region.find({type: "province", name:entity['省']}, '_id').exec(function (err, results) {
                                        entity.provinceId = results[0]._id;
                                        callbackInner4(err, results);
                                    });
                                }else {
                                    callbackInner4(null, null);
                                }
                            },

                            function (callbackInner4) {

                                if (entity['市']) {
                                    Region.find({type: "city", name:entity['市']}, '_id').exec(function (err, results) {
                                        entity.cityId = results[0]._id;
                                        callbackInner4(err, results);
                                    });
                                }else {
                                    callbackInner4(null, null);
                                }
                            },

                            function (callbackInner4) {

                                if (entity['区/县']) {
                                    Region.find({type: "county", name:entity['区/县']}, '_id').exec(function (err, results) {
                                        entity.countyId = results[0]._id;
                                        callbackInner4(err, results);
                                    });
                                }else {
                                    callbackInner4(null, null);
                                }
                            }


                        ], callbackInner3);

                    },

                    function (callbackInner3) {

                        var option = {communityName:entity['小区名称']};
                        Community.count(option, function(err, result) {
                            res = result == 1;
                            callbackInner3(err,result);
                        });
                    },

                    function (callbackInner3) {

                        if (res) {
                            var data = {};
                            if (entity.provinceId) data.provinceId = entity.provinceId;
                            if (entity.cityId) data.cityId = entity.cityId;
                            if (entity.countyId) data.countyId = entity.countyId;

                            //if (entity['生效日期']) data.dateEffective = entity['生效日期'];

                            if (entity['行政子区域']) data.subdistrict = entity['行政子区域']; //行政子区域
                            if (entity['开发商']) data.developer = entity['开发商']; //开发商
                            if (entity['小区住宅类型']) data.propertyType = entity['小区住宅类型']; //小区住宅类型
                            if (entity['物业']) data.property = entity['物业']; //物业
                            if (entity['小区占地面积']) data.constructionArea = Number(entity['小区占地面积']); //小区占地面积
                            if (entity['户数']) data.households = Number(entity['户数']);
                            if (entity['小区建造日期']) data.dateBuild = new Date(entity['小区建造日期']); // 小区建造日期
                            if (entity['小区描述']) data.desc = entity['小区描述'];  //小区描述
                            if (entity['价格(元/平方)']) data.price = Number(entity['价格(元/平方)']); //价格(元/平方)
                            if (entity['绿化率']) data.greenRate = Number(entity['绿化率']); //绿化率
                            if (entity['租']) data.rent = Number(entity['租']); //租
                            if (entity['出售']) data.sale = Number(entity['出售']); //出售
                            data.pinyin = getPinyin(entity['小区名称']);
                            data.pinyinShort = getPinyinShort(entity['小区名称']);

                            var option = {communityName:entity['小区名称']};

                            Community.update(option, data, function(err, result){

                                if (err) {
                                    failureAry.push(entity['省'] + ',' +entity['市'] + ',' + entity['区/县'] +':' + entity['小区名称'] + '  ');
                                }

                                if (num == (all - 1)) {
                                    var temp = new CommunityImport({allRecord:all,failure:failureAry});
                                    temp.save(function(err, result) {
                                        num += 1;
                                        callbackInner3(err, result);
                                    });
                                }else {
                                    num += 1;
                                    callbackInner3(err, result);
                                }


                            });
                        }else {
                            failureAry.push(entity['市'] +':' + entity['小区名称'] + ',');
                            logger.debug("all:");
                            logger.debug(all + "," + num);
                            if (num == (all - 1)) {
                                var temp = new CommunityImport({allRecord:all,failure:failureAry});
                                temp.save(function(err, result) {
                                    num += 1;
                                    callbackInner3(err, result);
                                });
                            }else {
                                num += 1;
                                callbackInner3("小区信息重复", null);
                            }
                        }
                    }
                ], callbackInner2);

            },callbackInner);

        }], callback);
};


exports.supplementStatusUpdateService = function (req, callback) {

    logger.debug(req.body);

    var id = req.body.id;
    var status = req.body.status;
    var name = req.body.name;
    var phone =req.body.phone;
    var address = req.body.address;
    var user = req.body.user;
    var community = req.body.community;
    var supplyId =  req.body.supplyId;

    var res = status ? (name && phone && user && community) : true;

    if (!(id && res)) return callback("缺少id等", null);

    if (!status) {
        return CommunitySupplement.update({_id: id}, {status: status}, function(err,data){

            User.findOne({_id: user}, function (err, result) {

                toolUtil.pushCustomerServiceMessage({
                    _id: user,
                    huanxinUserName: result.huanxinUserName
                }, '你补充修改的'+name+'信息未被采纳，还有机会哦，试试其他的也可以的哦～');
                callback(err,data);
            });

        });
    }

    logger.debug(phone);

    var exist = false;
    var phoneList = [];

    async.series([

        function (callbackInner) {

            Community.find({_id:community},function(err, result) {

                phoneList = result[0].phoneList ? result[0].phoneList:[];
                phoneList.forEach(function(temp){
                    if (temp._id == supplyId) {
                        temp.phoneNo = phone;
                        if (address) temp.address = address;
                        if (user) temp.user = user;
                        exist = true;
                    }
                });

                if (!exist) {
                    var data = {name:name, phoneNo:phone, user:user};
                    if (address) data.address = address;
                    phoneList.push(data);
                }
                //result[0] delete
                //delete result[0]['_id'];
                //for (var item in result[0]) {
                //    if (result[0][item] == id) {
                //        delete option[item];
                //    }
                //};
                //result[0].phoneList = phoneList;
                //var list = JSON.parse(JSON.stringify(phoneList));

                logger.debug('id--'+id);
                logger.debug(phoneList);
                Community.update({_id:community}, {phoneList: phoneList}, callbackInner);

            });
        },

        function (callbackInner) {

            User.findOne({_id: user}, function (err, result) {

                toolUtil.pushCustomerServiceMessage({
                    _id: user,
                    huanxinUserName: result.huanxinUserName
                }, '你补充修改的'+name+'信息已成功被采纳，你真的是太棒了～');
                callbackInner();
            });
        },

        function (callbackInner) {

            toolUtil.addScoreMessage(user, 1, 36);
            CommunitySupplement.update({_id: id}, {status: status}, callbackInner);
        }

    ], callback);

};


exports.supplementListService = function (req, callback) {


    var body = req.body;
    var size = Number(req.params.size);
    var index = (Number(req.params.page) - 1) * size;

    var option = {};
    if (body.community) option.community = body.community;

    if (body.status){
        if(body.status ==2){
            option['$or'] = [{status:{$exists: false}},{status:null}];
        }else {
            option.status = body.status;
        }
    }

    var sortType = {status: 1, dateCreated: -1};
    logger.debug(option);
    async.series([

        function (callbackInner) {
            CommunitySupplement.count(option, function (err, count) {

                if (err) {
                    callbackInner(err, null);
                }else {
                    var temp = {count: count, totalPage:Math.ceil(count/size)};
                    callbackInner(err, temp);
                }
            });
        },

        function (callbackInner) {
            CommunitySupplement.find(option)
                .populate('createdBy', 'nickName')
                .populate('community', 'communityName')
                .sort(sortType).skip(index).limit(size).exec(callbackInner);

        }], callback);

};


exports.applyListListService = function(req ,callback) {

    var body = req.body;
    var size = Number(req.params.size);
    var index = (Number(req.params.page) - 1) * size;
    var paged = (req.params.size && req.params.page);

    var option = body;
    var sortType = paged ? {dateCreated:-1} : {};

    if (option.communityName) option.communityName = new RegExp(option.communityName);
    logger.debug(option);
    async.series([

        function (callbackInner) {

            Apply.count(option, function (err, count) {

                if (err) {
                    callbackInner(err, null);
                }else {
                    var temp = {count: count, page:Math.ceil(count/size)};
                    callbackInner(err, temp);
                }
            });
        },
        function (callbackInner) {

            Apply.find(option)
                .populate('user', '_id userName email mobilePhone nickName')
                .populate('city', '_id name')
                .populate('county', '_id name')
                .sort(sortType).skip(index).limit(size).exec(function (err, results) {

                    if (err) {
                        callbackInner(err);
                    } else {
                        callbackInner(null, results);
                    }
                });


        }], callback);


};


exports.applyPassService = function (req, callback) {

    var id = req.body.applyId;
    var status = req.body.status;
    var user = req.body.user;
    var phone = req.body.phone;
    var msg = req.body.msg;


    if (!id) return callback("缺少id", null);


    CommunityApplications.update({_id: id}, {status: status}, function (err, result) {

        if (err) {
            callback(err);
        } else {

            if (req.body.type == 2) {

                UserCommunity.findOne({user: user, type: 2}).populate('community', '_id communityName')
                    .exec(function (err, result2) {

                        var pushData = {
                            userId: user,
                            msgType: 'open_other_community',
                            communityId: result2.community._id
                        };
                        logger.debug(pushData);
                        toolUtil.putMessageTagPushMQ(pushData);

                    });

            };

            //发送短消息
            if (msg && phone)  toolUtil.putMessageSMS(phone, msg, '1');

            callback();
        }
    });


};

exports.applyPassCheckService = function (req, callback){

    var body = req.body

    UserCommunity.findOne({user: body.user, type: body.type}).populate('community', '_id communityName')
        .exec(function (err, result) {
            logger.debug(result);

            callback(null,result);

        })

}


exports.applyRejectService = function (req, callback) {

    var id = req.body.applyId;
    var status = req.body.status;
    var phone = req.body.phone;
    var msg = req.body.msg;

    if (!id) return callback("缺少id", null);

    CommunityApplications.update({_id: id}, {status: status}, function (err, result) {

        if(err){
            callback(err);
        }else{

            //发送短消息
            if (msg && phone)  toolUtil.putMessageSMS(phone, msg,'0');

            var pushData = {
                userId: req.body.user,
                msgType: 'open_other_community'
            };
            logger.debug(pushData);
            toolUtil.putMessageTagPushMQ(pushData);
            callback();
        }
    });
};


//exports.getCommunityLocation = function(req, callback)
//{
//    var opt = {};var communityOpt = {};
//    if(req.params) {
//        opt.type = req.params.type;
//        opt.name = new RegExp(req.params.name);
//    }
//    logger.debug(opt);
//    Region.findOne(opt, '_id name').exec(function (err, region) {
//        if(opt&&opt.type!= 'country') {
//            communityOpt[opt.type +'Id'] = region._id;
//        }else if(opt){
//            communityOpt[opt.type] = region._id;
//        }
//        communityOpt["isValid"]=true;
//        communityOpt["isInit"]=true;
//        logger.debug(region);
//        logger.debug(communityOpt);
//
//        Community.find(communityOpt,'location communityName').exec(function(err,result){
            //var data = [];
            //async.eachSeries(result, function iterator(community, callbackInner) {
            //    logger.debug(community);
            //    if(community) {
            //        community.location.longitude = community.location.longitude - 0.0065;
            //        community.location.latitude = community.location.latitude - 0.0065;
            //        //data.name = community.communityName;
            //        data.push(community)
            //        callbackInner(null,community);
            //    }
            //    callbackInner(null,null);
            //}, function done(err,result) {
            //    callback(err,data);
            //});
//            callback(err,result);
//        });
//    });
//};

exports.getCommunityCount = function(req,callback)
{
    logger.debug(req.url);
    var type =  req.params.type;
    var dataAll = [];
    //type: 'country', 'province', 'city', 'county'

    Cache.cacheGet('/rest/v1.0/mis/community/communityCountList/city',function(err,result)
    {
        logger.debug(JSON.parse(result));
        if(err) {
            callback(err,null);
        }
        if(result) {
            callback(null,JSON.parse(result));
        }else
        {
            Region.find({type: type}, '_id name').exec(function (err, region) {
                async.mapSeries(region,function(region,callbackInner){
                    var opt = {},allopt = {};
                    opt["isValid"]=true;
                    opt["isInit"]=true;
                    if(type!= 'country') {
                        allopt[type +'Id'] = region._id;
                        opt[type +'Id'] = region._id;
                    }else {
                        allopt[type] = region._id;
                        opt[type] = region._id;
                    }
                    console.log(opt);
                    Community.count(opt,function(err,count){
                        if(err) logger.debug(err);
                        logger.debug(count);
                        if(count){
                            Community.findOne(opt,'location cityId').populate('cityId').exec(function(err,result) {
                                Community.count(allopt,function(err,all){
                                    Region.findOne({_id:result.cityId.parentId}).exec(function(err,province) {
                                        if(err) callbackInner(err,null);

                                        var data = {};
                                        data.province = province.name;
                                        data.name = region.name;
                                        data.all   =all;
                                        data.count = count;
                                        //data.location = result.location;
                                        data.location={};
                                        data.location.longitude = result.location.longitude - 0.0065;
                                        data.location.latitude = result.location.latitude - 0.0065;
                                        callbackInner(null,data);
                                        dataAll.push(data);
                                    });
                                });

                            });
                        }else {
                            callbackInner(null,null);
                        }
                    });
                },function(error,result) {
                    if(error) {
                        callback(error,null);
                    }
                    logger.debug(req.url);
                    Cache.cacheSet('/rest/v1.0/mis/community/communityCountList/city',JSON.stringify(dataAll), function (err, result) {
                        if (err) {
                            logger.error('Failed to generate the '+req.url+' code for - ' + mobilePhone);
                        } else {
                            logger.debug('Succeeded to generate the '+req.url+' code for - ' + mobilePhone);
                        }
                    }, 4233600);
                    callback(null,dataAll);
                });
            });
        }
    });


};

exports.getCommunityByLocation =function(req,callback)
{
    var LocSouthWest  = req.body.SouthWest;
    var LocNorthEast  = req.body.NorthEast;
    var Loc2Address   = req.body.Loc2Address;
    var Loc = {};
    Loc.LocSouthWest = LocSouthWest;
    Loc.LocNorthEast = LocNorthEast;
    /***
     *  db.community.find({location:{$within:{$center:[[121.4453170000000000,31.1992330000000000],0.015]}}}).count();  //范围索引
     *  db.community.find({location:{$within:{$box:[[121.456808,31.203776],[121.440329,31.180281]]}}}).count();       //box模型索引
     */
    //Community.find({location:{$within:{$center:[Loc,0.025]}},isValid:true,isInit:true},'_id location communityName').exec(function(err,result) {
    logger.debug(Loc2Address);
    Cache.cacheGet(Loc2Address,function(err,result)
    {
        if(err) callback(err);
        if(result) {
            callback(null,JSON.parse(result));
        } else{
            Community.find({location:{$within:{$box:[LocSouthWest,LocNorthEast]}},isValid:true,isInit:true},'_id location').exec(function(err,result) {
                if(err) {
                    callback(new Error(err),null);
                }
               //  var data = [];
               /// async.eachSeries(result, function iterator(community, callbackInner) {
               //     User.count({community:community._id},function(err,count) {
               //         logger.debug(result._id,count);
               //         if(count) {
               //             console.log('人数为'+count);
               //         }else {
               //             console.log('人数为'+count);
               //         }
               //         var commun = {};
               //         if(community) {
               //             commun.location = {};
               //             commun.location.longitude = community.location.longitude - 0.0065;
               //             commun.location.latitude = community.location.latitude - 0.0065;
               //             commun.name  =  community.communityName;
               //             commun.persons = count;
               //             data.push(commun)
               //             callbackInner();
               //         }
               //         callbackInner();
               //     });
               // }, function done(err,result) {

                Cache.cacheSet(Loc2Address,JSON.stringify(result),function(err,info)
                {
                    if (err) {
                        logger.error('Failed to generate the '+err+' code for - ');
                    } else {
                        logger.debug('Succeeded to generate the '+info+' code for - ');
                    }
                },3000);
            //        callback(err,data);
            //    });
                callback(null,result)
            });
        }
    });
}
